package com.hxl.servlet;

import com.hxl.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文的乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        //得到Session
        HttpSession session = req.getSession();

        //给Session中存东西
        session.setAttribute("name",new Person("哈哈哈",1));
        //获取session的ID
        String sessionId = session.getId();
        //判断session是不是新创建的
        if(session.isNew()){
            resp.getWriter().write("Session创建成功,ID为"+sessionId);
        }else{
            resp.getWriter().write("session已经在服务器中存在了"+sessionId);
        }

        /*
            //Session创建的时候做了什么事情
            Cookie cookieid = new Cookie("JSESSIONID", sessionId);
            resp.addCookie(cookieid);
         */


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
